# -*- coding: utf-8 -*-

'''eof
name:法定代表人变更
code:R17_EG_CorporationChangeCheck_WHB
tableName:
columnName:
groups:弱规则>工商信息校验
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import json
from datetime import datetime


def FormatData(tableName):
    try:
        eg = EG_DSJ.get("data").get("R1103V3")[0].get(tableName)
        return eg if isinstance(eg, list) else [{}]
    except:
        return [{}]


def formatDate(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None


def getRule09():
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    itemList = [u'法人代表变更', u'负责人变更（法定代表人、负责人、首席代表、个体户经营者、投资人、合伙事务执行人等变更）',
                u'法定代表人（负责人）变更', u'执行合伙企业事务的合伙人', u'法定代表人变更', u'法定代表人姓名',
                u'负责人（法定代表人、首席代表、合伙事务执行人等）变更', u'法定代表人(负责人、董事长、首席代表)变更',
                u'负责人变更（法定代表人、负责人、首席代表、合伙事务执行人等变更）', u'法定代表人（负责人、董事长、首席代表）变更',
                u'法定代表人', u'执行合伙企业事务的合伙', u'法定代表人(负责人、独资投资人)',
                u'负责人变更（法定代表人、负责人、首席代表、合伙事务执行人等变更）变更', u'负责人变更', u'法定代表人（负责人）',
                u'经营者姓名', u'负责人变更（法定代表人、负责人、首席代表、个体户经营者、投资人、合伙事务执行人等变更）']
    basic_list = FormatData("alterList")
    relativeDate = ratingRequest.get("relativeDate")
    relativeDate = formatDate(relativeDate)
    nowDate = datetime.now().strftime('%Y%m%d')
    if basic_list == [{}]:
        return u'缺失值'
    else:
        if relativeDate is None:
            raise ValueError(u"网贷传输的数据字段relativeDate缺失或不符合要求")
        if len(basic_list) >= 1:
            resultList = []
            flag = False
            for i in basic_list:
                altDate = i.get("altDate")
                altItem = i.get("altItem")
                if altDate not in null_type_list and altItem not in null_type_list \
                        and formatDate(altDate[0:10]) not in null_type_list:
                    altDate = formatDate(altDate[0:10])
                    flag = True
                    if altItem in itemList and relativeDate < altDate <= nowDate:
                        resultList.append(1)

            return sum(resultList) if flag else u'缺失值'
        else:
            return 0


if __name__ == "__main__":
    file_obj = open(r'../data/WHB/R17_EG_CorporationChangeCheck_WHB/EG_DSJ.json', 'r')
    ratingRequest = {"relativeDate": "2014.09.09", "legalPerson": u"朱为广", "legalPersonIdCard": "510102196706108511"}
    content = file_obj.read()
    EG_DSJ = json.loads(content, strict=False)
    aa = getRule09()
    print aa

result = getRule09()
